package com.newlink.building.common_base.gson

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter

/**
 * @Author: Jake
 * @Date: 2023-04-27
 * @Description:
 */
object Base_GsonUtils {

    fun createGson(): Gson {
        val builder = GsonBuilder().apply {
            registerTypeAdapter(Int::class.java, IntegerDefaultAdapter())
            registerTypeAdapter(String::class.java, StringDefaultAdapter())
        }
        return builder.create()
    }

    class IntegerDefaultAdapter : TypeAdapter<Int>() {
        override fun write(jsonWriter: JsonWriter, integer: Int) {
            jsonWriter.value("$integer")
        }

        override fun read(jsonReader: JsonReader): Int {
            return try {
                jsonReader.nextString().toInt()
            } catch (e: NumberFormatException) {
                e.printStackTrace()
                -1
            }
        }
    }

    class StringDefaultAdapter : TypeAdapter<String>() {
        override fun write(out: JsonWriter, value: String) {
            out.value(value)
        }

        override fun read(jsonReader: JsonReader): String {
            return if (jsonReader.peek() == JsonToken.NULL) {
                jsonReader.nextNull()
                ""
            } else {
                jsonReader.nextString()
            }
        }
    }

}